import 'package:enter_prise_web/util/MyDio.dart';
import 'package:enter_prise_web/widgets/timeline.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

import 'more_controller.dart';

class More extends StatefulWidget {
  const More({super.key});

  @override
  State<More> createState() => _MoreState();
}

class _MoreState extends State<More> with SingleTickerProviderStateMixin {
  final TextEditingController _controller = TextEditingController();
  final TextEditingController _titleController = TextEditingController();
  final MyDio myDio = MyDio();
  bool isShowButton = false;
  int count = 0;
  final FocusNode _focusNode1 = FocusNode();
  final FocusNode _focusNode2 = FocusNode();
  late Animation<double> _animation;
  late AnimationController animationController;
  late CurvedAnimation _curvedAnimation;
  double height = 350;

  @override
  void dispose() {
    super.dispose();
    animationController.dispose();
    _focusNode1.dispose();
    _focusNode2.dispose();
  }

 @override
  void initState() {
    super.initState();
    // 创建一个AnimationController，它用来控制动画
    animationController = AnimationController(
        vsync: this, duration: const Duration(microseconds: 500));
    // 创建一个CurvedAnimation，它用来控制动画的曲线
    _curvedAnimation = CurvedAnimation(
        parent: animationController, curve: Curves.fastOutSlowIn);
    // 创建一个Tween，它用来控制动画的起始和结束值
    _animation = Tween(begin: 350.0, end: 150.0).animate(_curvedAnimation)
      ..addListener(() {
        setState(() {
          height = _animation.value;
        });
      });
    // 为_focusNode2添加监听器，当获取到焦点时，取消_focusNode1的焦点，并使动画向前移动，同时设置isShowButton为true
    _focusNode2.addListener(() {
      if (_focusNode2.hasFocus) {
        _focusNode1.unfocus();
        animationController.forward();
        setState(() {
          isShowButton = true;
        });
      } else {
        isShowButton = false;
      }
    });
    // 为_focusNode1添加监听器，当获取到焦点时，取消_focusNode2的焦点，并使动画向前移动，同时设置isShowButton为true
    _focusNode1.addListener(() {
      if (_focusNode1.hasFocus) {
        _focusNode2.unfocus();
        animationController.forward();
        setState(() {
          isShowButton = true;
   @override
  void initState() {
    super.initState();
    // 创建一个AnimationController，它用来控制动画
    animationController = AnimationController(
        vsync: this, duration: const Duration(microseconds: 500));
    // 创建一个CurvedAnimation，它用来控制动画的曲线
    _curvedAnimation = CurvedAnimation(
        parent: animationController, curve: Curves.fastOutSlowIn);
    // 创建一个Tween，它用来控制动画的起始和结束值
    _animation = Tween(begin: 350.0, end: 150.0).animate(_curvedAnimation)
      ..addListener(() {
        setState(() {
          height = _animation.value;
        });
      });
    // 为_focusNode2添加监听器，当获取到焦点时，取消_focusNode1的焦点，并使动画向前移动，同时设置isShowButton为true
    _focusNode2.addListener(() {
      if (_focusNode2.hasFocus) {
        _focusNode1.unfocus();
        animationController.forward();
        setState(() {
          isShowButton = true;
        });
      } else {
        isShowButton = false;
      }
    });
    // 为_focusNode1添加监听器，当获取到焦点时，取消_focusNode2的焦点，并使动画向前移动，同时设置isShowButton为true
    _focusNode1.addListener(() {
      if (_focusNode1.hasFocus) {
        _focusNode2.unfocus();
        animationController.forward();
        setState(() {
          isShowButton = true;
        });
      } else {
        isShowButton = false;
      }
    });
  }     });
      } else {
        isShowButton = false;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
        child: IntrinsicHeight(
      child: Stack(children: [
        Column(
          children: [
            const Text(
              "通知",
              style: TextStyle(fontSize: 20),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              padding: const EdgeInsets.all(8.0),
              height: 300,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
              ),
              child: GetBuilder<moreController>(
                  id: "notice_list",
                  builder: (controler) {
                    return ListView.builder(
                      itemCount: controler.noticelist.length,
                      itemBuilder: (context, index) {
                        var notice = controler.noticelist[index];
                        return timeline(
                          bgColor: Colors.orange,
                          isLast: index == controler.noticelist.length - 1,
                          title: notice['title'],
                          subtitle: notice['time'],
                          content: notice['content'],
                        );
                      },
                    );
                  }),
            ),
          ],
        ),
        Container(
          padding: EdgeInsets.only(top: isShowButton ? 100 : 300),
          child: Column(
            children: [
              Container(
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    color: Colors.white,
                  ),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          const Padding(
                            padding: EdgeInsets.only(left: 8.0),
                            child: Text(
                              "标题：",
                              style: TextStyle(fontSize: 20),
                            ),
                          ),
                          SizedBox(
                            width: 150,
                            height: 40,
                            child: TextField(
                              autofocus: true,
                              focusNode: _focusNode1,
                              controller: _titleController,
                              inputFormatters: [InputFormatter(true)],
                              decoration: const InputDecoration(
                                  hintText: "请输入标题",
                                  contentPadding: EdgeInsets.only(left: 10),
                                  border: OutlineInputBorder()),
                            ),
                          ),
                        ],
                      ),
                      const Row(
                        children: [
                          Padding(
                            padding: EdgeInsets.all(8.0),
                            child: Text(
                              "通知内容：",
                              style: TextStyle(fontSize: 16),
                            ),
                          ),
                        ],
                      ),
                      TextField(
                        controller: _controller,
                        keyboardType: TextInputType.multiline,
                        maxLines: 3,
                        maxLength: 100,
                        maxLengthEnforcement: MaxLengthEnforcement.none,
                        focusNode: _focusNode2,
                        autofocus: false,
                        // inputFormatters: [InputFormatter(false)],
                        onChanged: (value) {
                          setState(() {
                            count = value.length;
                          });
                        },
                        buildCounter: (context,
                            {required currentLength,
                            required bool isFocused,
                            maxLength}) {
                          return Text.rich(
                            TextSpan(children: [
                              TextSpan(
                                  text: '$currentLength',
                                  style: TextStyle(
                                      color: currentLength > maxLength!
                                          ? Colors.red
                                          : Colors.black)),
                              const TextSpan(text: ' / '),
                              TextSpan(text: '$maxLength')
                            ]),
                          );
                        },
                        decoration: const InputDecoration(
                            hintText: "输入你的留言",
                            border: OutlineInputBorder(
                                borderSide: BorderSide(color: Colors.black)),
                            focusedBorder: OutlineInputBorder(
                              borderSide:
                                  BorderSide(width: 1, color: Colors.redAccent),
                            )),
                      ),
                      isShowButton
                          ? Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                TextButton(
                                  child: const Text("取消"),
                                  onPressed: () {
                                    setState(() {
                                      count = 0;
                                    });
                                    _controller.clear();
                                    _focusNode1.unfocus();
                                    _focusNode2.unfocus();
                                  },
                                ),
                                Expanded(
                                  child: Container(),
                                ),
                                TextButton(
                                  child: const Text("确定"),
                                  onPressed: () async {
                                    if (_controller.text.isEmpty ||
                                        _titleController.text.isEmpty) {
                                      Fluttertoast.showToast(msg: "输入内容不能为空");
                                      return;
                                    }
                                    var response = await myDio
                                        .requestData("/notice/add",method: 'POST', params: {
                                      "title": _titleController.text,
                                      "content": _controller.text,
                                      "time":
                                          DateTime.now().millisecondsSinceEpoch
                                    });
                                    if (response.statusCode == 200) {
                                      Fluttertoast.showToast(msg: "发布成功");
                                      _focusNode1.unfocus();
                                      _focusNode2.unfocus();
                                      _controller.clear();
                                      _titleController.clear();
                                      setState(() {
                                        isShowButton = false;
                                      });
                                    }
                                  },
                                ),
                              ],
                            )
                          : const SizedBox.shrink(),
                    ],
                  ))
            ],
          ),
        ),
      ]),
    ));
  }
}

class InputFormatter extends TextInputFormatter {
  final bool? isTitle;

  late int count;

  InputFormatter(this.isTitle);
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    if (oldValue.text.isEmpty && newValue.text.isEmpty) {
      return oldValue;
    }
    if (newValue == "") {
      return newValue;
    }
    //判断字符是否为数字

    switch (isTitle) {
      case true:
        count = 10;
        break;
      case false:
        count = 100;
        break;
      default:
        count = 100;
        break;
    }

    if (newValue.text.length >= count) {
      return oldValue;
    }
    return newValue;
  }
}
